package net.youdi.gateway.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import net.youdi.gateway.context.KeyStore;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.AntPathMatcher;

import java.nio.charset.StandardCharsets;

public class GateWayUtil {
    private static final AntPathMatcher pathMatcher = new AntPathMatcher();
    /**
     * get Real Ip Address
     * @param request ServerHttpRequest
     * @return
     * @author Evans
     */
    public static String getIpAddress(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String ip = headers.getFirst("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("X-Real-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddress().getAddress().getHostAddress();
        }
        if(ip != null && ip.length() > 15 && ip.contains(",")){
            ip = ip.substring(0,ip.indexOf(","));
        }
        return ip;
    }

    /**
     * get offline cache key
     * @return
     */
    public static String getOfflineCacheKey(String ip, int port){
        if(ip != null){
            return ip+":"+port;
        }
        return null;
    }

    public static boolean match(String url, String[] mathUrls) {
        if (mathUrls != null && mathUrls.length > 0) {
            for (String permission : mathUrls) {
                if (pathMatcher.match(permission, url)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean isAndroid(String userAgent) {
        return userAgent.contains("okhttp-okgo/jeasonlzy") || userAgent.contains("PrototypeAndroid");
    }

    public static boolean isWeb(String userAgent) {
        return userAgent.startsWith("Mozilla")||userAgent.contains("Dart");
    }
    public static boolean isIos(String userAgent) {
        return userAgent.contains("iOS")&&(userAgent.contains("iPhone")||userAgent.contains("iPod")||userAgent.contains("iPad"));
    }
}